package com.buobao.controller;

import com.buobao.entity.Member;
import com.buobao.service.MemberService;
import com.buobao.utils.MD5Utils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Controller
public class MemberController {
    @Resource
    private MemberService memberService;

    @GetMapping("/register.html")
    public ModelAndView showRegister() {
        return new ModelAndView("/register");
    }

    @PostMapping("/registe")
    @ResponseBody
    public Map registe(String vc, String username, String password, String nickname, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String kaptchaCode = (String) session.getAttribute("kaptchaCode");
        Map result = new HashMap<String,Object>();
        if (vc==null || kaptchaCode == null || !kaptchaCode.equalsIgnoreCase(vc)) {
            result.put("code","vc01");
            result.put("msg","验证码错误");
        } else {
            Member member = new Member();
            member.setNickName(nickname);
            member.setUsername(username);
            member.setPassword(password);
            member.setCreateTime(new Date());
            memberService.insertMember(member);

            result.put("code","0");
            result.put("msg","success");
        }
        return result;
    }

    @GetMapping("/login.html")
    public ModelAndView login() {
        return new ModelAndView("/login");
    }


    @PostMapping("/check_login")
    @ResponseBody
    public Map checkLogin(String username,String password,HttpServletRequest request){
        HashMap<String, Object> result = new HashMap<>();
        Member member = memberService.selectMemberByUsernameAndPassword(username, password);
        if (member == null) {
            result.put("code","lg01");
            result.put("msg","登录失败");
        } else {
            result.put("code","0");
            result.put("msg","success");
            HttpSession session = request.getSession();
            session.setAttribute("member",member);
        }
        return result;
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.removeAttribute("member");
        return "redirect:/";
    }
}